import os
import sys
import time
import random
import threading

SAVE_ROOT = "~/test/"

def do_commond(commond):
    os.system(commond)


def start():
    devices = getDevices()

    for s in devices:
        t1 = threading.Thread(target=do_device, args=(s,))
        t1.start()
        print "s:" + s
        # do_device(s)


def do_device(s):
    saveDir = SAVE_ROOT + s + "/"
    do_commond("mkdir " + saveDir)
    count = 0
    while count < 50:
        count += 1
        j = 0
        time.sleep(2)
        print("count:" + str(count))
        # intputTap(s, '540', '500')
        intputTap(s, '540', '480')

        while j < 40:
            print("swipe: " + str(j))
            j += 1
            time.sleep(2)
            runXSwipe(s)
            time.sleep(3)
            runYSwipe(s)

        now_time = time.strftime("%H-%M-%S")
        # screencap(s, now_time)
        time.sleep(3)
        inputBack(s)
        time.sleep(1)
        inputBack(s)
        time.sleep(1)
        intputTap(s, '950', '550')
        time.sleep(2)
        intputTap(s, '950', '950')
        time.sleep(6)


def getDevices():
    t_f = os.popen("adb devices")
    # print t_f.read()
    line = t_f.readline()
    arr = []
    while line:
        if line.find("device") != -1 and line.find("devices") == -1:
            line = line.replace("device", "").strip()
            line = line.replace("\n", "")
            arr.append(line)
            print line
        # print(line, end = '') python 3
        line = t_f.readline()
    return arr


def intputTap(s, x, y):
    cmd = "adb -s " + s + " shell input tap " + x + " " + y
    print cmd
    do_commond(cmd)


def inputSwipe(s, x1, y1, x2, y2):
    cmd = "adb -s " + s + " shell input swipe " + \
        str(x1) + " " + str(y1) + " " + str(x2) + " " + str(y2)
    do_commond(cmd)


def getTmpPoint(min, max):
    #x=random.uniform(60, 480)
    #y=random.uniform(270, 690)
    return random.uniform(min, max)


def runYSwipe(s):
    x1 = getTmpPoint(60, 480)
    y1 = getTmpPoint(270, 690)
    # print(x1)
    # print(y1)
    x2 = x1
    y2 = y1 + 50
    inputSwipe(s, x1, y1, x2, y2)


def runXSwipe(s):
    x1 = getTmpPoint(60, 480)
    y1 = getTmpPoint(270, 690)
    # print(x1)
    # print(y1)
    x2 = x1 + 50
    y2 = y1
    inputSwipe(s, x1, y1, x2, y2)


def inputBack(s):
    cmd = "adb -s " + s + " shell input keyevent 4"
    do_commond(cmd)


def screencap(s, name):
    cmd = "adb -s " + s + \
        " shell /system/bin/screencap -p /sdcard/" + str(name) + ".png"
    do_commond(cmd)
    cmd = "adb -s " + s + " pull /sdcard/" + str(name) + ".png " + SAVE_ROOT + s + "/"
    do_commond(cmd)
    cmd = "adb -s " + s + " shell rm /sdcard/" + str(name) + ".png"
    do_commond(cmd)

if __name__ == '__main__':
    start()
